﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common.Logging;

namespace KeepAliveHttp.Http
{
    /// <summary>
    /// 一个Web客户端连接
    /// </summary>
    public class WebClientConnection
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(WebClientConnection));

        public WebClientConnection(AsyncResult asyncResult)
        {
            this.CreateTime = DateTime.Now;
            this.SessionId = Guid.NewGuid().ToString().Substring(0, 5);
            this.AsyncResult = asyncResult;
        }

        /// <summary>
        /// 链接创建时间
        /// </summary>
        public DateTime CreateTime { get; set; }
        /// <summary>
        /// 会话唯一标识
        /// </summary>
        public string SessionId { get; set; }
        /// <summary>
        /// 每个连接对应的异步结果
        /// </summary>
        public AsyncResult AsyncResult { get; set; }
        /// <summary>
        /// 是否已经完成
        /// </summary>
        public bool IsCompleted
        {
            get
            {
                if (this.AsyncResult == null)
                    return false;
                return this.AsyncResult.IsCompleted;
            }
        }
        /// <summary>
        /// 给客户端发送消息
        /// </summary>
        /// <param name="message"></param>
        public void Send(string message)
        {
            if (this.IsCompleted)
            {
                _logger.Warn("连接已经完成，无法发送消息");
                return;
            }
            this.AsyncResult?.Send(message);
        }
    }
}